﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Threading;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraTab;
using Microsoft.Office.Interop.Word;

namespace SoufunData
{
    public partial class BProjectDetailForm : DevExpress.XtraEditors.XtraForm
    {
        public BProjectDetailForm(string projectName)
        {
            InitializeComponent();
            this.Text =this.Text+"    当前项目："+projectName;
            imageList2.Images.Add(Properties.Resources.WordFile_52x51);
            _proName = projectName;

          
        }

        private void BProjectDetailForm_Load(object sender, EventArgs e)
        {
            lb_ProjectName.Text = _proName;
            string[] tcpconfig = ConfigClass.GetFtpConfig();
            ftpClient = new FTPclient(tcpconfig[0],
            tcpconfig[1], tcpconfig[2]);
            Thread t = new Thread(LoadData){IsBackground = true};
            t.Start();
        }

        private  readonly Hashtable ImageList 
            = Hashtable.Synchronized(new Hashtable());

        private SqlClass _sqlClass = new SqlClass();
        private string _proName;
        private string _rootPath =
            System.Windows.Forms.Application.ExecutablePath.Remove(
            System.Windows.Forms.Application.ExecutablePath.LastIndexOf('\\'))
                  + "\\" + "FileCache";

        private FTPclient ftpClient;
        private bool _isWordOpenning;
        private bool _isLoadingFile;
        private bool _isLoadingImages;
        private bool _isDeletingImages;
        private bool _isDeletingFiles;

        private Hashtable _delHt = new Hashtable();
        private int _delCount = 0;

        private void LoadData()
        {
            DataSet dsBasic = _sqlClass.GetBProjectBasicInfo(_proName);
            DataSet dsBusinessManage = _sqlClass.GetBbusinessmanage(_proName);
            DataSet dsPlanning = _sqlClass.GetBplanningdesign(_proName);
            DataSet dsSummarize = _sqlClass.GetBsummarize(_proName);
             
            string filePath = "";
            if (dsBasic!=null && dsBasic.Tables.Count!=0 
                && dsBasic.Tables[0].Rows.Count>0)
            {
                DataRow row = dsBasic.Tables[0].Rows[0];
                filePath = row["FilePath"].ToString();
                BeginInvoke(new MethodInvoker(() =>
                    {
                     
                        lb_Address.Text = row["Address"].ToString();
                        lb_AdministratiVeregion.Text = row["AdministratiVeregion"].ToString();
                        lb_BigCompanyAroud.Text = row["BigCompanyAroud"].ToString();
                        lb_BuildBusiness.Text = row["BuildBusiness"].ToString();
                        lb_BusRouteCount.Text = row["BusRouteCount"].ToString();
                        lb_BusRouteName.Text = row["BusRouteName"].ToString();
                        lb_BusStationName.Text = row["BusStationName"].ToString();
                        lb_BusinessCircles.Text = row["BusinessCircles"].ToString();
                        lb_BusinessDesignCompany.Text = row["BusinessDesignCompany"].ToString();
                        lb_BusinessType.Text = row["BusinessType"].ToString();
                        lb_CirclesLevel.Text = row["CirclesLevel"].ToString();
                        lb_DistanceToStation.Text = row["DistanceToStation"].ToString();
                        lb_HolidayAfternoonPerson.Text = row["HolidayAfternoonPerson"].ToString();
                        lb_HolidayMonitorTime.Text = row["HolidayMonitorTime"].ToString();
                        lb_HolidayMorningPerson.Text = row["HolidayMorningPerson"].ToString();
                        lb_ManagementCompany.Text = row["ManagementCompany"].ToString();
                        lb_MetroRouteCount.Text = row["MetroRouteCount"].ToString();
                        lb_MetroRouteName.Text = row["MetroRouteName"].ToString();
                        lb_MetroStationName.Text = row["MetroStationName"].ToString();
                        lb_OpenTime.Text = row["OpenTime"].ToString();
                        lb_ParkingOverCount.Text = row["ParkingOverCount"].ToString();
                        lb_ParkingOverPrice.Text = row["ParkingOverPrice"].ToString();
                        lb_ParkingUnderCount.Text = row["ParkingUnderCount"].ToString();
                        lb_ParkingUnderPrice.Text = row["ParkingUnderPrice"].ToString();
                        lb_PropertyCompany.Text = row["PropertyCompany"].ToString();
                        lb_PropertyPrice.Text = row["PropertyPrice"].ToString();
                        lb_SellState.Text = row["SellState"].ToString();
                        lb_SupportingAroud.Text = row["SupportingAroud"].ToString();
                        lb_WeekDayAfternoonPerson.Text = row["WeekDayAfternoonPerson"].ToString();
                        lb_WeekDayMonitorTime.Text = row["WeekDayMonitorTime"].ToString();
                        lb_WeekDayMorningPerson.Text = row["WeekDayMorningPerson"].ToString();                
                    }));                 
            }

            if (dsSummarize!=null && dsSummarize.Tables.Count!=0
                && dsSummarize.Tables[0].Rows.Count>0)
            {
                DataRow row = dsSummarize.Tables[0].Rows[0];
                BeginInvoke(new MethodInvoker(() =>
                    {
                        lbs_Feature.Text = row["Feature"].ToString();
                        lbs_Orientate.Text = row["Orientate"].ToString();
                        lbs_Range.Text = row["Range"].ToString();
                        memoEdits_Advantage.Text = row["Advantage"].ToString();
                        memoEdits_Disadvantage.Text = row["Disadvantage"].ToString();        
                    }));                
            }

            if (dsBusinessManage!=null && dsBusinessManage.Tables.Count!=0
                && dsBusinessManage.Tables[0].Rows.Count>0)
            {
                DataRow row = dsBusinessManage.Tables[0].Rows[0];
                BeginInvoke(new MethodInvoker(() =>
                    {
                        lbm_AddRate.Text = row["AddRate"].ToString();
                        lbm_Business.Text = row["Business"].ToString();
                        lbm_CheckOutType.Text = row["CheckOutType"].ToString();
                        lbm_ConditionerPrice.Text = row["ConditionerPrice"].ToString();
                        lbm_CooperateType.Text = row["CooperateType"].ToString();
                        lbm_HireRate.Text = row["HireRate"].ToString();
                        lbm_HireYears.Text = row["HireYears"].ToString();
                        lbm_KouDian.Text = row["KouDian"].ToString();
                        lbm_MailHire.Text = row["MailHire"].ToString();
                        lbm_ManageState.Text = row["ManageState"].ToString();
                        lbm_Price.Text = row["Price"].ToString();
                        lbm_PropertyPrice.Text = row["PropertyPrice"].ToString();
                        lbm_SaleType.Text = row["SaleType"].ToString();
                        lbm_SellRate.Text = row["SellRate"].ToString();

                    }));
            }
           
            if (dsPlanning!=null && dsPlanning.Tables.Count>0
                && dsPlanning.Tables[0].Rows.Count>0)
            {
                DataRow row = dsPlanning.Tables[0].Rows[0];
                BeginInvoke(new MethodInvoker(() =>
                    {
                        Control[] controls= this.Controls.Find("xtraTabPage_planDesign", true);
                        XtraTabPage tabPage = controls[0] as XtraTabPage;
                        foreach (Control control in tabPage.Controls)
                        {
                            if (control.Name.StartsWith("lbp_"))
                            {
                              
                                control.Text = row[control.Name.Replace("lbp_", "")].ToString().Replace("\n","；");
                               
                            }                        
                        }
                    })); 
            } 

            LoadImage(); 
            LoadFile(filePath);
            
        }

       private void LoadImage()
       {
           _isLoadingImages = true;
           DataSet dsImage = _sqlClass.GetImageList(_proName);
           imageList1.Images.Clear();
           ImageList.Clear();
           int imgCount = 0;
           #region  下载图片
           if (dsImage != null && dsImage.Tables.Count != 0
               && dsImage.Tables[0].Rows.Count > 0)
           {
               DataRow row = dsImage.Tables[0].Rows[0];
               string strTrafficImages = row["TrafficImages"].ToString();
               string strFloorImages = row["FloorImages"].ToString();
               string strInsideDecorate = row["InsideDecorate"].ToString();
               string strConfigImages = row["ConfigImages"].ToString();
               string strElseImages = row["ElseImages"].ToString();
               string strEntranceImages = row["EntranceImages"].ToString();
               string strOutFacade = row["OutFacade"].ToString();
               string strWCImages = row["WCImages"].ToString();
               //--------------------
               //string rootPath = Application.ExecutablePath
               //    .Remove(Application.ExecutablePath.LastIndexOf('\\')) 
               //    +"\\" + "ImageCache";
               DirectoryInfo rootDir = new DirectoryInfo(_rootPath);
               if (!rootDir.Exists)
               {
                   Directory.CreateDirectory(_rootPath);
               }
               string projectPath = _rootPath + "\\" + _proName;
               DirectoryInfo projectDir = new DirectoryInfo(projectPath);
               if (!projectDir.Exists)
               {
                   Directory.CreateDirectory(projectPath);
               }
               string trafficPath = projectPath + "\\交通图";
               DirectoryInfo trafficDir = new DirectoryInfo(trafficPath);
               if (!trafficDir.Exists)
               {
                   Directory.CreateDirectory(trafficPath);
               }
               List<string> addList = new List<string>();
               // string downloadUrl = ConfigClass.ReadImageDownLoadUrl();
               string[] trafficImgs = strTrafficImages.Split('|');
               List<string> trafficlist = new List<string>();
               foreach (string img in trafficImgs)
               {
                   if (img.Trim() != "")
                   {
                       trafficlist.Add(img);
                       imgCount++;
                   }

                   if (img.Trim() != "" &&
                       trafficDir.GetFiles(img).Length == 0)
                   {
                       addList.Add("交通图/" + img);
                       
                   }
               }
               ImageList["交通图"] = trafficlist;

               string floorPath = projectPath + "\\楼层平面图";
               DirectoryInfo floorDir = new DirectoryInfo(floorPath);
               if (!floorDir.Exists)
               {
                   Directory.CreateDirectory(floorPath);
               }
               string[] floorImgs = strFloorImages.Split('|');
               List<string> floorList = new List<string>();
               foreach (string img in floorImgs)
               {
                   if (img.Trim() != "")
                   {
                       imgCount++;
                       floorList.Add(img);
                   }
                   
                   if (img.Trim() != "" &&
                       floorDir.GetFiles(img).Length == 0)
                   {
                       addList.Add("楼层平面图/" + img);
                     
                   }
               }
               ImageList["楼层平面图"] = floorList;

               string inSidePath = projectPath + "\\内部装修图";
               DirectoryInfo inSideDir = new DirectoryInfo(inSidePath);
               if (!inSideDir.Exists)
               {
                   Directory.CreateDirectory(inSidePath);
               }
               string[] inSideImgs = strInsideDecorate.Split('|');
               List<string> InsideList = new List<string>();
               foreach (string img in inSideImgs)
               {
                   if (img.Trim() != "")
                   {
                       imgCount++;
                       InsideList.Add(img);
                   }
                   if (img.Trim() != "" &&
                       inSideDir.GetFiles(img).Length == 0)
                   {                      
                       addList.Add("内部装修图/" + img);
                   }
               }
               ImageList["内部装修图"] = InsideList;

               string configPath = projectPath + "\\配套图";
               DirectoryInfo configDir = new DirectoryInfo(configPath);
               if (!configDir.Exists)
               {
                   Directory.CreateDirectory(configPath);
               }
               string[] configImgs = strConfigImages.Split('|');
               List<string> configList = new List<string>();
               foreach (string img in configImgs)
               {
                   if (img.Trim() != "")
                   {
                       imgCount++;
                       configList.Add(img);
                   }
                   if (img.Trim() != "" &&
                       configDir.GetFiles(img).Length == 0)
                   {
                       addList.Add("配套图/" + img);
                      
                   }
               }
               ImageList["配套图"] = configList;

               string elsePath = projectPath + "\\其他";
               DirectoryInfo elseDir = new DirectoryInfo(elsePath);
               if (!elseDir.Exists)
               {
                   Directory.CreateDirectory(elsePath);
               }
               string[] elseImgs = strElseImages.Split('|');
               List<string> elseList = new List<string>();
               foreach (string img in elseImgs)
               {
                   if (img.Trim() != "")
                   {
                       elseList.Add(img);
                       imgCount++;
                   }
                   if (img.Trim() != "" &&
                       elseDir.GetFiles(img).Length == 0)
                   {
                       addList.Add("其他/" + img);
                       
                   }
               }
               ImageList["其他"] = elseList;

               string entrancePath = projectPath + "\\入口、电梯图";
               DirectoryInfo entranceDir = new DirectoryInfo(entrancePath);
               if (!entranceDir.Exists)
               {
                   Directory.CreateDirectory(entrancePath);
               }
               string[] entranceImgs = strEntranceImages.Split('|');
               List<string> entranceList = new List<string>();
               foreach (string img in entranceImgs)
               {
                   if (img.Trim() != "")
                   {
                       imgCount++;
                       entranceList.Add(img);
                   }
                   if (img.Trim() != "" &&
                       entranceDir.GetFiles(img).Length == 0)
                   {
                       addList.Add("入口、电梯图/" + img);
                      
                   }
               }
               ImageList["入口、电梯图"] = entranceList;

               string outfacadePath = projectPath + "\\外立面图";
               DirectoryInfo outfacadeDir = new DirectoryInfo(outfacadePath);
               if (!outfacadeDir.Exists)
               {
                   Directory.CreateDirectory(outfacadePath);
               }
               string[] outFacadeImgs = strOutFacade.Split('|');
               List<string> outFacadeList = new List<string>();
               foreach (string img in outFacadeImgs)
               {
                   if (img.Trim() != "")
                   {
                       outFacadeList.Add(img);
                       imgCount++;
                   }
                   if (img.Trim() != "" &&
                       outfacadeDir.GetFiles(img).Length == 0)
                   {
                       addList.Add("外立面图/" + img);
                  
                   }
               }
               ImageList["外立面图"] = outFacadeList;

               string wcImgPath = projectPath + "\\卫生间图";
               DirectoryInfo wcImgDir = new DirectoryInfo(wcImgPath);
               if (!wcImgDir.Exists)
               {
                   Directory.CreateDirectory(wcImgPath);
               }
               string[] wcImgs = strWCImages.Split('|');
               List<string> wcList = new List<string>();
               foreach (string img in wcImgs)
               {
                   if (img.Trim() != "")
                   {
                       wcList.Add(img);
                       imgCount++;
                   }
                   if (img.Trim() != "" &&
                       wcImgDir.GetFiles(img).Length == 0)
                   {
                       addList.Add("卫生间图/" + img);
                      
                   }
               }
               ImageList["卫生间图"] = wcList;

               foreach (string addImg in addList)
               {
                   try
                   {
                       bool result = ftpClient.Download(
                       _proName + "/" + addImg,
                       projectPath + "\\" + addImg.Replace("/", "\\"), true);
                   }
                   catch (Exception ex)
                   {
                       XtraMessageBox.Show("文件下载失败！");
                       return;
                   } 
               }
           }

           #endregion

           if (imgCount==0)
           {
               BeginInvoke(new MethodInvoker(() =>
                   {
                       label_notice.Text = "该项目尚无图片！";
                       //label_notice.Visible = false;
                       imgeCombo_imgType.Enabled = false;
                       btn_addNewImage.Enabled = true;
                   }));
               return;
           }
           BeginInvoke(new MethodInvoker(() =>
               { 
                   imgeCombo_imgType.Enabled = true;
               }));
           int index = 0;
           if (imgeCombo_imgType.SelectedIndex==0)
           {
               BeginInvoke(new MethodInvoker(() =>
                   {
                       foreach (DictionaryEntry  ss in ImageList )
                       {
                   
                           List<string> imgs = ss.Value as List<string>;
                   
                                foreach (string img in imgs)
                                {
                                    string filePath = _rootPath +"\\"+ _proName 
                                        + "\\" + ss.Key + "\\" + img;
                                    Bitmap bitmap = new Bitmap(filePath); 
                                    imageList1.Images.Add(img, bitmap);
                                  

                                    ListViewItem item = new ListViewItem();
                                    item.Name = filePath;
                                    item.Text = img;
                                    item.ImageIndex = index;
                                    item.Tag = ss.Key;
                                    listView_images.Items.Add(item);

                                    index++;
                                    btn_addNewImage.Enabled = true;
                                    imgeCombo_imgType.Enabled = true;
                                    label_notice.Text = "共" + listView_images.Items.Count + "张图片";
                                } 
                       }
                   }));       
           }
           else
           {
               string strType = imgeCombo_imgType.SelectedItem.ToString();
                BeginInvoke(new MethodInvoker(() =>
                   {
                       List<string> imgs = ImageList[strType] as List<string>;
                       foreach (string img in imgs)
                       {
                           string filePath = _rootPath + "\\" + _proName
                               + "\\" + strType + "\\" + img;
                           Bitmap bitmap = new Bitmap(filePath);
                           imageList1.Images.Add(img, bitmap);
                           ListViewItem item = new ListViewItem();
                           item.Name = filePath;
                           item.Text = img;
                           item.ImageIndex = index;
                           item.Tag = strType;
                           listView_images.Items.Add(item);
                           index++;
                       }
                       btn_addNewImage.Enabled = true;
                       imgeCombo_imgType.Enabled = true;
                       label_notice.Text = "共" + listView_images.Items.Count + "张图片";
                   })); 
           }
           _isLoadingImages = false;
       }

       private void LoadFile(object objPath)
       {
           _isLoadingFile = true;
           string filePath = objPath as string;
           if (filePath.Trim()=="")
           {
               filePath = _sqlClass.GetBfilePathFromBasic(_proName);
           }
           if (filePath==null||filePath.Trim() == "")
           {
               BeginInvoke(new MethodInvoker(() =>
                   {
                       label_noticeFile.Text = "该项目尚无文件！";
                       btn_addFile.Enabled = true;
                   }));
               _isLoadingFile = false;
               return;
           }
           string projectPath = _rootPath + "\\" + _proName;
           DirectoryInfo projectDir = new DirectoryInfo(projectPath);
           if (!projectDir.Exists)
           {
               Directory.CreateDirectory(projectPath);
           }
           string strfilePath = projectPath + "\\文件";
           DirectoryInfo fileDir = new DirectoryInfo(strfilePath);
           if (!fileDir.Exists)
           {
               Directory.CreateDirectory(strfilePath);
           }
           List<string> fileList = new List<string>();
           List<string> addList = new List<string>();
           string[] files = filePath.Split('|');
           foreach (string file in files)
           {
               if (file.Trim() != "" && !fileList.Contains(file))
               {
                   fileList.Add(file);
               }
               if (file.Trim() != "" &&
                   fileDir.GetFiles(file).Length == 0)
               {
                   addList.Add("文件/" + file);
               }
           }

           foreach (string addfile in addList)
           {
               try
               {
                   bool result = ftpClient.Download(
                   _proName + "/" + addfile,
                   projectPath + "\\" + addfile.Replace("/", "\\"), true);
               }
               catch (Exception ex)
               {
                   XtraMessageBox.Show("文件下载失败！"); 
               }
           }

            BeginInvoke(new MethodInvoker(() =>
            {
                foreach (string ss in fileList)
                {
                    ListViewItem item = new ListViewItem();
                    item.Name = ss;
                    item.Text = ss.Substring(ss.LastIndexOf("\\") + 1);
                    string fileType = ss.Substring(ss.LastIndexOf('.') + 1);
                    switch (fileType)
                    {
                        case "doc":
                            item.ImageIndex = 0;
                            break;
                        case "docx":
                            item.ImageIndex = 0;
                            break;
                        default:
                            item.ImageIndex = 0;
                            break;
                    }         
                    listView_file.Items.Add(item);                  
                }
               
                label_noticeFile.Text = "共"+listView_file.Items.Count+"个文件";
                btn_addFile.Enabled = true;
               
            }));
           _isLoadingFile = false;
       }


       private void imgeCombo_imgType_SelectedIndexChanged(object sender, EventArgs e)
       {
           listView_images.Items.Clear();
           LoadImage();
       }

       private void btn_addNew_Click(object sender, EventArgs e)
       {
           BUpdateImageForm form = new BUpdateImageForm(_proName);
          // form.MdiParent = this.MdiParent;
           form.ShowDialog();
           
           if (form.DialogResult==DialogResult.Yes)
           { 
               btn_addNewImage.Enabled = false;
               imgeCombo_imgType.Enabled = false;
               label_notice.Text = "正在重新加载图片...";
               listView_images.Items.Clear();
                
               Thread t = new Thread(LoadImage) { IsBackground = true };
               t.Start();                
           }

       }

       private void btn_addFile_Click(object sender, EventArgs e)
       {
           BUpdateFileForm form = new BUpdateFileForm(_proName);
           //form.MdiParent = this.MdiParent;
           form.ShowDialog();
           if (form.DialogResult==DialogResult.Yes)
           {
               btn_addFile.Enabled = false;
               label_noticeFile.Text = "正在重新加载文件...";
               listView_file.Items.Clear();
               Thread t = new Thread(LoadFile);
               t.IsBackground = true;
               t.Start("");
           }
       }

       private void listView2_MouseDoubleClick(object sender, MouseEventArgs e)
       {
           if (e.Button==MouseButtons.Left)
           {
               ListViewItem item = listView_file.SelectedItems[0];
               if (item!=null)
               {

                richEditControl1.Text = "正在加载内容...";
                richEditControl1.Visible = true;
                 //string file="C:\\Users\\Christ\\Desktop\\soufang\\新计划.doc";
                string file = _rootPath + "\\" + _proName + "\\文件\\" + item.Name;
                string strData = Common.Doc2Text(file);
                if (strData==null)
                {
                    XtraMessageBox.Show("打开文档失败，请检测您的电脑是否安装office，或您本机的Office版本是否过低！");
                    return;
                }
                   richEditControl1.Text = strData; 
                   btn_closeWord.Visible = true;
                   _isWordOpenning = true;
               }
           }
       }

       private void btn_closeWord_MouseHover(object sender, EventArgs e)
       {
           this.Cursor = Cursors.Hand;
       }

       private void btn_closeWord_MouseLeave(object sender, EventArgs e)
       {
           this.Cursor = Cursors.Default;
       }

       private void btn_closeWord_Click(object sender, EventArgs e)
       {
           richEditControl1.Text = "";
           richEditControl1.Visible = false;
           btn_closeWord.Visible = false;
           _isWordOpenning = false;
       }

       

       private void xtraTabControl1_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
       {
           if (e.Page != xtraTabPage_ytbj)
           {
               btn_closeWord.Visible = false;
           }
           else
           {
               btn_closeWord.Visible = _isWordOpenning;
           }
       }

       #region  文件-右键菜单
       //*****************右键显示菜单
       private void listView_file_MouseUp(object sender, MouseEventArgs e)
       {
           if (e.Button == MouseButtons.Right && e.Clicks == 1)
           {
               popupMenu_fileRight.ShowPopup(Cursor.Position);
               barBtnItem_AddNewFile.Enabled = !_isLoadingFile;
               barBtnItem_DeleteFile.Enabled = !_isLoadingFile;
               barBtnItem_RefreshFile.Enabled = !_isLoadingFile;
               bool hasSelected = listView_file.SelectedItems.Count > 0;
               barBtnItem_DeleteFile.Enabled = hasSelected && !_isDeletingFiles;
               barBtnItem_OpenFileDir.Enabled = hasSelected;
               barBtnItem_OpenByOffice.Enabled = hasSelected;

           }
       }

        //*****************添加新文件
       private void barBtnItem_AddNewFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           btn_addFile_Click(null,null);
       }

       //*****************刷新文件
       private void barBtnItem_RefreshFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           if (!_isLoadingFile)
           {
               BeginInvoke(new MethodInvoker(() =>
                   {
                       btn_addFile.Enabled = false;
                       label_noticeFile.Text = "正在重新加载文件...";
                       listView_file.Items.Clear();
                   }));               
               Thread t = new Thread(LoadFile);
               t.IsBackground = true;
               t.Start("");    
           } 
       }

       //**************打开文件所在文件夹
       private void barBtnItem_OpenFileDir_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           string dirpath = _rootPath +"\\"+_proName+ "\\文件";
           if (!Directory.Exists(dirpath))
           {
               XtraMessageBox.Show("未找到所在文件夹："+dirpath);
               return;
           }
           try
           {
               System.Diagnostics.Process.Start(dirpath);
           }
           catch (Exception ex)
           {
               XtraMessageBox.Show(ex.Message);
           } 
       }
     
        //****************用 Office Word 打开文件
       private void barBtnItem_OpenByOffice_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           if (listView_file.SelectedItems.Count==0)
           {
               return;
           }           
           string filePath = _rootPath+"\\"+_proName+"\\文件\\"+
               listView_file.SelectedItems[0].Name;
           try
           {
               System.Diagnostics.Process.Start(filePath);
           }
           catch (Exception ex)
           {
               XtraMessageBox.Show("打开文件时发生异常：" + ex.Message);
           }
           
       }

       //*************************删除文件
        private List<string> _delFilesList = new List<string>();
        
       private void barBtnItem_DeleteFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           if (XtraMessageBox.Show("是否确定删除选中的文件？", "警告：",
             MessageBoxButtons.YesNo) == DialogResult.No)
           {
               return;
           } 
           _isDeletingFiles = true;
           barBtnItem_DeleteFile.Enabled = false;
           _delFilesList.Clear();
           foreach (ListViewItem item in listView_file.SelectedItems)
           {
              
               string file = item.Text;
               _delFilesList.Add(file);               
           }
           Thread t = new Thread(DeleteFile) { IsBackground = true };
           t.Start();
       }

       #endregion

       #region 图片-右键菜单

       private void listView_images_MouseUp(object sender, MouseEventArgs e)
       {
           if (e.Button == MouseButtons.Right && e.Clicks == 1)
           {
               popupMenu_imageRight.ShowPopup(Cursor.Position);
               barBtnItem_AddImages.Enabled = !_isLoadingImages;             
               barBtnItem_RefreshImage.Enabled = !_isLoadingImages;
               bool hasSelected = listView_images.SelectedItems.Count > 0;
               barBtnItem_DeleteImage.Enabled = !_isLoadingImages
                 && !_isDeletingImages&&hasSelected;
               barBtnItem_OpenImageDir.Enabled = hasSelected;
               

           }
       }
        //**************添加图片
       private void barBtnItem_AddImages_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           btn_addNew_Click(null,null);
       }
        //**************删除图片

     
       private void barBtnItem_DeleteImage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           if (XtraMessageBox.Show("是否确定删除选中的图片？","警告：",
               MessageBoxButtons.YesNo)== DialogResult.No)
           {
               return;
           }
           _delHt.Clear();
           _delCount = 0;
           _isDeletingImages = true;
           barBtnItem_DeleteImage.Enabled = false;
           foreach (ListViewItem item in listView_images.SelectedItems)
           {
               _delCount++;
               string type = item.Tag.ToString();
               string name = item.Text;
               List<string> imglist = new List<string>();
               if (_delHt.Contains(type))
               {
                   imglist = _delHt[type] as List<string>;
               }
               imglist.Add(name);
               _delHt[type] = imglist;
           }
           Thread t = new Thread(DeleteImages){IsBackground = true};
           t.Start();
       }
        //**************打开图片所在文件夹
       private void barBtnItem_OpenImageDir_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           if (listView_images.SelectedItems.Count==0)
           {
               return;
           }
           ListViewItem item = listView_images.SelectedItems[0];
           string path = item.Name;
           path = path.Remove(path.LastIndexOf("\\"));
           if (!Directory.Exists(path))
           {
               XtraMessageBox.Show("图片所在文件夹不存在，请检查：" + path);
           }
           try
           {
               System.Diagnostics.Process.Start(path);
           }
           catch (Exception)
           {
                
           }            
       }
        //**************刷新图片列表
       private void barBtnItem_RefreshImage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
       {
           if (!_isLoadingImages)
           {
               BeginInvoke(new MethodInvoker(() =>
                   {
                       btn_addNewImage.Enabled = false;
                       imgeCombo_imgType.Enabled = false;
                       label_notice.Text = "正在刷新图片...";
                       listView_images.Items.Clear();        
                   }));               
               
               Thread t = new Thread(LoadImage) { IsBackground = true };
               t.Start();   
           }
            
       }
       #endregion

       
        private void DeleteImages()
        { 
            int succeedCount = 0; 
            foreach (DictionaryEntry de in _delHt)
            {
                string type = de.Key.ToString();
                string column = "";
                switch (type)
                {
                    case "交通图":
                        column = "TrafficImages";
                        break;
                    case "楼层平面图":
                        column = "FloorImages";
                        break;
                    case "内部装修图":
                        column = "InsideDecorate";
                        break;
                    case "配套图":
                        column = "ConfigImages";
                        break;
                    case "其他":
                        column = "ElseImages";
                        break;
                    case "入口、电梯图":
                        column = "EntranceImages";
                        break;
                    case "外立面图":
                        column = "OutFacade";
                        break;
                    case "卫生间图":
                        column = "WCImages";
                        break;
                    default:
                        column = "TrafficImages";
                        break;
                }
                List<string> delList = de.Value as List<string>;
                foreach (string imgName in delList)
                {
                    bool result = _sqlClass.BImagesUpdate(_proName,
                       column, "|"+imgName);
                    if (result)
                    {                                                
                        succeedCount++;
                    }
                }
            }
            if (_delCount==succeedCount)
            {
                XtraMessageBox.Show("成功删除" + _delCount + "张图片！");
            }
            else
            {
                XtraMessageBox.Show("成功删除" + _delCount + "张图片！"+
                    (_delCount-succeedCount)+"张删除失败,请尝试刷新后重新删除！");
            }
            _isDeletingImages = false;
            barBtnItem_RefreshImage_ItemClick(null,null);
        }
        private void DeleteFile()
        {
            int succeed = 0;
            foreach (string file in _delFilesList)
            {
                bool result = _sqlClass.BusinessBasicFilePathDelete(_proName,
                       "|"+file);
                if (result)
                {
                    succeed++;
                }
            }
            if (_delFilesList.Count == succeed)
            {
                XtraMessageBox.Show("成功删除" + _delFilesList.Count + "个文件！");
            }
            else
            {
                XtraMessageBox.Show("成功删除" + _delCount + "个文件！" +
                    (_delFilesList.Count - succeed) + "个删除失败,请尝试刷新后重新删除！");
            }
            _isDeletingFiles = false;
            barBtnItem_RefreshFile_ItemClick(null, null);
        }

    }
     
}